package com.jin;

import com.jin.utils.Config;
import com.jin.utils.PdfUtils;
import com.jin.utils.WorldUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


public class AppSwing {
    private final JTextField path;
    private final JTextArea success = new JTextArea(16, 40);
    private static AppSwing appSwing ;

    private static String FILE_CHOOSE_PATH = "";
    private static final String WINDOWS_STYLE = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
    private static final String NIMBUS_STYLE = "javax.swing.plaf.nimbus.NimbusLookAndFeel";

    public static void appendLog(String log){
        appSwing.success.append(log + "\n");
    }

    public void initStyle(String style){
        try {
            // 设置Windows风格外观
            UIManager.setLookAndFeel(style);
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
            e.printStackTrace();
        }
    }

    public AppSwing(){
        initStyle(NIMBUS_STYLE);
        appSwing = this;
        JFrame frame = new JFrame("安心签合同生成(980254542@qq.com)");
        JLabel label = new JLabel("需要生成的目录");
        label.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        path = new JTextField("");
        path.setPreferredSize(new Dimension(370,30));
        path.setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));

        JButton upload = new JButton("...");
        upload.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        upload.setPreferredSize(new Dimension(30,30));

        JButton gen = new JButton("执行");
        gen.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        gen.setPreferredSize(new Dimension(60,30));

        upload.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                JFileChooser fileChooser = new JFileChooser();
                String selectPath = path.getText();
                File selectPathFile = new File(selectPath);
                if(selectPathFile.exists()){
                    if(selectPathFile.isDirectory()){
                        FILE_CHOOSE_PATH = selectPath;
                    }else{
                        File parentFile = selectPathFile.getParentFile();
                        FILE_CHOOSE_PATH = parentFile.getAbsolutePath();
                    }
                }
                fileChooser.setCurrentDirectory(new File(FILE_CHOOSE_PATH));
                fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);

                fileChooser.setMultiSelectionEnabled(true);
                int returnValue = fileChooser.showOpenDialog(null);

                if (returnValue == JFileChooser.APPROVE_OPTION) {
                    File[] selectedFiles = fileChooser.getSelectedFiles();
                    if(selectedFiles.length > 1){
                        for (File item : selectedFiles) {
                            if(item.isDirectory()){
                                JOptionPane.showMessageDialog(path, "多选不能包含文件夹");
                                return;
                            }
                        }
                    }

                    if(fileChooser.getSelectedFiles().length > 1){
                        File[] files = fileChooser.getSelectedFiles();
                        StringBuilder builder = new StringBuilder();
                        for (File file : files) {
                            if(PdfUtils.isDoc(file.getAbsolutePath())){
                                builder.append("\"").append(file.getAbsolutePath()).append("\" ");
                            }
                        }
                        if(builder.length() == 0){
                            JOptionPane.showMessageDialog(path, "选择的文件中不包含word文档，请选择word文档");
                        }else{
                            path.setText(builder.toString());
                        }
                        FILE_CHOOSE_PATH = files[0].getParentFile().getAbsolutePath();
                    }else{

                        FILE_CHOOSE_PATH = fileChooser.getSelectedFile().getAbsolutePath();
                        File file = new File(fileChooser.getSelectedFile().getAbsolutePath());
                        if(file.isDirectory() || PdfUtils.isDoc(fileChooser.getSelectedFile().getAbsolutePath())){
                            path.setText(fileChooser.getSelectedFile().getAbsolutePath());
                        }else{
                            JOptionPane.showMessageDialog(path, "请选择word文档");
                        }
                    }
                }

            }
        });

        frame.setLayout(new FlowLayout(FlowLayout.LEFT));
        frame.add(label);
        frame.add(path);

        frame.add(upload);

        frame.add(gen);



        JScrollPane jScrollPane = new JScrollPane(success);

        jScrollPane.setPreferredSize(new Dimension(500,300));
        success.setEditable(false);
        frame.add(jScrollPane);

        gen.addActionListener(e -> {
            String fileDirs = path.getText();
            if(fileDirs == null || fileDirs.trim().length() == 0){
                JOptionPane.showMessageDialog(gen, "请选择文件夹或文件");
                return;
            }
            success.setText("");
            success.paintImmediately(success.getBounds());
            fileDirs = fileDirs.trim();

            String[] split = fileDirs.split("\" \"");

            List<File> files = new ArrayList<>();
            int errCount = 0;
            for (String item : split) {
                String path = item.replaceAll("\"", "");
                File file = new File(path);
                if(!file.exists()){
                    JOptionPane.showMessageDialog(gen, path + " 文件夹或文件不存在");
                    return;
                }
                PdfUtils.handleFiles(files,file);
            }

            for (File item : files) {
                String name = item.getName().substring(0,item.getName().lastIndexOf("."));
                String pdf = item.getParentFile().getAbsolutePath() + "\\" + name + ".pdf";
                String pdfText = item.getParentFile().getAbsolutePath() + "\\" + name + "-GEN.pdf";
                try {
                    WorldUtils.genPdf(item.getAbsolutePath(),pdf);
                    PdfUtils.createForm(pdf,pdfText);
                } catch (Exception ex) {
                    success.append("error:" + item.getAbsolutePath() + "\n");
                    success.append("error:" + ex + "\n");
                    StackTraceElement[] stackTrace = ex.getStackTrace();
                    StringBuilder builder = new StringBuilder();
                    for (StackTraceElement stackTraceElement : stackTrace) {
                        builder.append("    ").append(stackTraceElement.toString()).append("\n");
                    }
                    success.append("error:" + builder);
                    errCount ++;
                    continue;
                }
                new File(pdf).delete();
                success.append("success:" + item.getAbsolutePath() + "\n");
                success.paintImmediately(success.getBounds());
            }

            JOptionPane.showMessageDialog(gen, "执行完成，共完成" + files.size() + "个合同，其中正确：" + (files.size() - errCount) + "个，错误：" + errCount + "个");
        });

        frame.setSize(600, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        frame.setResizable(false);
    }

    public static void main(String[] args) {
        try {
            Config.init();
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null,"配置文件config.properties不存在");
            e.printStackTrace();
            return;
        }catch (Exception e){
            JOptionPane.showMessageDialog(null,e.getMessage());
            e.printStackTrace();
            return;
        }
        SwingUtilities.invokeLater(AppSwing::new);
    }
}
